package school.xauat.netty.组件.channel;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

/**
 * @author ：zsy
 * @date ：Created 2021/11/25 0:28
 * @description：
 */
@Slf4j
public class Client {

    public static void main(String[] args) throws InterruptedException {
        // 带有Future和Promise的都是异步方法的返回结果，用来处理结果
        ChannelFuture channelFuture = new Bootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StringEncoder());
                    }
                })
                // 连接到服务器
                // 异步非阻塞，main发起了调用，真正执行connect操作的是nio线程
                .connect("localhost", 8080);
        /*
        // sync()方法同步处理结果
        channelFuture.sync();
        log.debug("channel -> {}", channelFuture.channel());
        Channel channel = channelFuture.channel();
        channel.writeAndFlush("Hello Netty");
        */

        // 使用异步回调的方式
        channelFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                Channel channel = future.channel();
                log.debug("channel -> {}", channel);
                channel.writeAndFlush("Hello Netty");
            }
        });
    }

}
